from utils.misc import MAXFLOAT
from utils.interval import Interval


def compute_release_intervals(items, actions, verbose=True):
    """Analyzes pickup actions at tables to compute the release interval of items. Release intervals 
    are much smaller than delivery intervals because the items are arriving on a conveyor belt 
    which is supposed to never stop, since it is directly connected to the production line."""
    # build a list of release actions for each table
    release_actions = [action for action in actions if action.is_release]
    release_map = dict()
    for release in release_actions:
        if release.place not in release_map:
            release_map[release.place] = [release]
        else:
            release_map[release.place].append(release)
            
    # find out what is the smallest interval between releases from the same location
    min_delta = MAXFLOAT
    for _, rels in release_map.iteritems():
        for i in xrange(len(rels) - 1):
            min_delta = min(min_delta, rels[i+1].meta.timestamp - rels[i].meta.timestamp)
    if verbose:
        print "Minimum release interval:", min_delta
        
    # set the release interval around all item releases
    item_map = dict((item.id, item) for item in items)
    for release in release_actions:
        t = release.meta.timestamp
        for item_id in release.items:
            item = item_map[item_id]
            item.release = Interval.around(t, diameter=min_delta)
            
            
            